package config

import (
	"fmt"
	"github.com/spf13/viper"
	// 看清楚引入包，包的差异存在方法差异
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

// InitDB 创建数据库连接池
func InitDB() *gorm.DB {
	// 对应yaml文件字段
	driverName := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	/*
		连接数据库语句，这里使用了gorm框架
		可参考： https://gorm.io/zh_CN/docs/connecting_to_the_database.html
	*/
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset)
	db, err := gorm.Open(driverName, dsn)
	if err != nil {
		fmt.Println("fail err connect mysql", err.Error())
	}

	// 返回db连接
	return db
}
